package com.lzh.controller;

import cn.hutool.core.bean.BeanUtil;
import com.lzh.bean.LoginBean;
import com.lzh.bean.User1;
import com.lzh.common.bean.ResultBean;
import com.lzh.common.controller.BaseController;
import com.lzh.common.group.V;
import com.lzh.service.UserService;
import com.lzh.token.TokenTemplate;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@Api(tags = "用户管理")
@RequestMapping("/api")
public class UserController extends BaseController {
    @Autowired
    UserService userService;


    @Autowired
    TokenTemplate tokenTemplate;


    @ApiImplicitParam(name = "account",value = "账号",required = true,dataTypeClass = String.class,paramType = "query")
    @ApiOperation("检查账号是否存在")
    @GetMapping("/user/check")
    public ResultBean check(@RequestParam(required = true) String account){
        int i = userService.checkUser(account);
        String tmp = i==0?"no":"yes";
        return success("检查账号是否存在",tmp);
    }

    @ApiOperation("登录")
    @PostMapping("/user/login")
    public ResultBean login(@RequestBody LoginBean loginBean){

        //查询用户是否存在
        int i = userService.checkUser(loginBean.getAccount());

        //如果用户存在判断密码
        User1 user = userService.getUser(loginBean.getAccount());
        if (!user.getPassword().equals(loginBean.getPassword())){
            return fail("账号或密码错误");
        }

        //登录成功判断账户的状态
        if (user.getStatus()==2){
            return fail("该账号已经被禁用，请联系管理员");
        }
        //密码正确判断类型
        //把类型放到token中
        Map map = BeanUtil.beanToMap(user);
        //密码去掉
        map.remove("password");
        map.put("username",user.getAccount());
        map.remove("account");
        //判断角色
        String role = "";
        //放入token
        switch (user.getType()){
            case 1:
                if ("admin".equals(loginBean.getAccount())){
                    role = "admin";
                }else if ("sale".equals(loginBean.getAccount())){
                    role = "sale";
                }
                break;
            case 2:
                role = "customer";
                break;
            case 3:
                role = "supplier";
                break;
            case 4:
                role = "forwarder";
        }

        List<String> roleList = new ArrayList<>();
        roleList.add(role);
        map.put("roles",roleList);

        //生成token
        String token = tokenTemplate.generateToken(map);
        map.put("accessToken",token);

        return success("登录成功",map);
    }
}
